package struts.action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import struts.StrutsConfig;
import struts.form.ActionForm;
import struts.form.FullForm;
import struts.form.XmlBean;
import business.LoginAction;

/**
 * Servlet implementation class ActionServlet
 */
public class ActionServlet extends HttpServlet {
	private static final long	serialVersionUID	= 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ActionServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// request.setAttribute("x", name);
		// String url;
		// Action action = new LoginAction();
		// url = action.execute(request);
		// RequestDispatcher rd = request.getRequestDispatcher(url);
		// rd.forward(request, response);
		String path = this.getPath(request.getServletPath());
		System.out.println(path);
		Map<String, XmlBean> map = (Map<String, XmlBean>) this.getServletContext().getAttribute("struts");
		XmlBean xmlBean = map.get(path);
		String formClass = xmlBean.getFormBeanClass();
		ActionForm form = FullForm.full(formClass, request);
		String actionType = xmlBean.getActionType();
		Action action = null;
		String url = "";
		try {
			Class actionClass = Class.forName(actionType);
			action = (Action) actionClass.newInstance();
			url = action.execute(request, form, xmlBean.getActionForward());
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("控制器异常！");
			e.printStackTrace();
		}
		RequestDispatcher rd = request.getRequestDispatcher(url);
		rd.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		// TODO Auto-generated method stub
		this.doGet(request, response);
	}

	private String getPath(String servletPath) {

		return servletPath.split("\\.")[0];
	}
}
